package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOSSOperator;
import com.itheima.utils.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    // 注入minio配置文件
    @Autowired
    private MinioProperties minioProperties;

    // 注入minio client
    @Autowired
    private MinioClient client;


//    @PostMapping("/upload")
//    public Result upload(MultipartFile file) throws Exception {
//        log.info("文件上传: {}", file.getOriginalFilename());
//
//        //将文件交给OSS存储管理
//        String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
//        log.info("文件上传OSS, url: {}", url);
//
//        return Result.success(url);
//    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        // 获取文件真实的名称
        log.info("文件上传: {}", file.getOriginalFilename());
        String originalFileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 构建文件上传的相关信息
        PutObjectArgs args = PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                .object(originalFileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType()).build();
        // 将文件上传到minio服务器
        client.putObject(args);
        log.info("文件上传成功");
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + originalFileName;
        return Result.success(url);
    }

}
